using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using HuaRongDaoGame.Models;
using System.Linq; // Added for FirstOrDefault

namespace HuaRongDaoGame.Forms
{
    /// <summary>
    /// 自定义布局创建窗体
    /// </summary>
    public partial class CustomLayoutForm : Form
    {
        private GameBoard gameBoard;
        private GameLayout customLayout;
        private Block selectedBlock;
        private bool isPlacingBlock = false;
        private int nextBlockId = 1;

        /// <summary>
        /// 构造函数
        /// </summary>
        public CustomLayoutForm()
        {
            this.gameBoard = new GameBoard();
            this.customLayout = new GameLayout("", "", 1);
            InitializeCustomLayoutForm();
        }

        /// <summary>
        /// 初始化自定义布局窗体
        /// </summary>
        private void InitializeCustomLayoutForm()
        {
            this.Text = "创建自定义布局";
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            CreateControls();
        }

        /// <summary>
        /// 创建控件
        /// </summary>
        private void CreateControls()
        {
            // 标题
            var titleLabel = new Label
            {
                Text = "创建自定义布局",
                Font = new Font("Microsoft YaHei", 16, FontStyle.Bold),
                ForeColor = Color.DarkBlue,
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Top,
                Height = 40
            };

            // 主面板
            var mainPanel = new Panel
            {
                Dock = DockStyle.Fill,
                Padding = new Padding(10)
            };

            // 左侧控制面板
            var controlPanel = new Panel
            {
                Width = 200,
                Dock = DockStyle.Left,
                BorderStyle = BorderStyle.FixedSingle
            };

            // 右侧游戏棋盘
            var boardPanel = new Panel
            {
                Dock = DockStyle.Fill,
                BorderStyle = BorderStyle.FixedSingle
            };

            CreateControlPanel(controlPanel);
            CreateBoardPanel(boardPanel);

            mainPanel.Controls.Add(boardPanel);
            mainPanel.Controls.Add(controlPanel);

            this.Controls.Add(mainPanel);
            this.Controls.Add(titleLabel);
        }

        /// <summary>
        /// 创建控制面板
        /// </summary>
        private void CreateControlPanel(Panel panel)
        {
            int y = 10;

            // 布局名称
            var nameLabel = new Label
            {
                Text = "布局名称:",
                Location = new Point(10, y),
                Size = new Size(80, 20)
            };
            y += 25;

            var nameTextBox = new TextBox
            {
                Name = "nameTextBox",
                Location = new Point(10, y),
                Size = new Size(180, 20),
                Text = "自定义布局"
            };
            y += 35;

            // 方块类型选择
            var blockTypeLabel = new Label
            {
                Text = "方块类型:",
                Location = new Point(10, y),
                Size = new Size(80, 20)
            };
            y += 25;

            var blockTypeComboBox = new ComboBox
            {
                Name = "blockTypeComboBox",
                Location = new Point(10, y),
                Size = new Size(180, 20),
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            blockTypeComboBox.Items.AddRange(new object[]
            {
                "曹操 (2x2)",
                "关羽 (2x1)",
                "张飞 (2x1)",
                "赵云 (2x1)",
                "马超 (2x1)",
                "黄忠 (2x1)",
                "兵卒 (1x1)"
            });
            blockTypeComboBox.SelectedIndex = 0;
            y += 35;

            // 方块颜色选择
            var colorLabel = new Label
            {
                Text = "方块颜色:",
                Location = new Point(10, y),
                Size = new Size(80, 20)
            };
            y += 25;

            var colorComboBox = new ComboBox
            {
                Name = "colorComboBox",
                Location = new Point(10, y),
                Size = new Size(180, 20),
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            colorComboBox.Items.AddRange(new object[]
            {
                "红色",
                "蓝色",
                "绿色",
                "黄色",
                "紫色",
                "橙色",
                "青色"
            });
            colorComboBox.SelectedIndex = 0;
            y += 35;

            // 添加方块按钮
            var addBlockButton = new Button
            {
                Text = "添加方块",
                Location = new Point(10, y),
                Size = new Size(180, 30),
                BackColor = Color.LightBlue
            };
            addBlockButton.Click += (s, e) => StartPlacingBlock();
            y += 40;

            // 清除棋盘按钮
            var clearButton = new Button
            {
                Text = "清除棋盘",
                Location = new Point(10, y),
                Size = new Size(180, 30),
                BackColor = Color.LightCoral
            };
            clearButton.Click += (s, e) => ClearBoard();
            y += 40;

            // 保存布局按钮
            var saveButton = new Button
            {
                Text = "保存布局",
                Location = new Point(10, y),
                Size = new Size(180, 30),
                BackColor = Color.LightGreen
            };
            saveButton.Click += (s, e) => SaveLayout();
            y += 40;

            // 取消按钮
            var cancelButton = new Button
            {
                Text = "取消",
                Location = new Point(10, y),
                Size = new Size(180, 30),
                BackColor = Color.LightGray
            };
            cancelButton.Click += (s, e) => this.Close();

            // 添加控件到面板
            panel.Controls.AddRange(new Control[]
            {
                nameLabel, nameTextBox,
                blockTypeLabel, blockTypeComboBox,
                colorLabel, colorComboBox,
                addBlockButton, clearButton, saveButton, cancelButton
            });
        }

        /// <summary>
        /// 创建棋盘面板
        /// </summary>
        private void CreateBoardPanel(Panel panel)
        {
            panel.Paint += BoardPanel_Paint;
            panel.MouseClick += BoardPanel_MouseClick;

            panel.KeyDown += BoardPanel_KeyDown;
        }

        private void BoardPanel_KeyDown(object sender, KeyEventArgs e)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 棋盘绘制事件
        /// </summary>
        private void BoardPanel_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;
            g.Clear(Color.White);

            // 绘制网格
            DrawGrid(g, ((Panel)sender).Width, ((Panel)sender).Height);

            // 绘制方块
            DrawBlocks(g);
        }

        /// <summary>
        /// 绘制网格
        /// </summary>
        private void DrawGrid(Graphics g, int width, int height)
        {
            using (var pen = new Pen(Color.LightGray, 1))
            {
                // 绘制垂直线
                for (int x = 0; x <= GameBoard.BOARD_WIDTH; x++)
                {
                    int pixelX = x * 80;
                    g.DrawLine(pen, pixelX, 0, pixelX, height);
                }

                // 绘制水平线
                for (int y = 0; y <= GameBoard.BOARD_HEIGHT; y++)
                {
                    int pixelY = y * 80;
                    g.DrawLine(pen, 0, pixelY, width, pixelY);
                }
            }
        }

        /// <summary>
        /// 绘制方块
        /// </summary>
        private void DrawBlocks(Graphics g)
        {
            foreach (var block in gameBoard.Blocks)
            {
                var rect = new Rectangle(block.X * 80, block.Y * 80, block.Width * 80, block.Height * 80);
                
                using (var brush = new SolidBrush(block.Color))
                {
                    g.FillRectangle(brush, rect);
                }
                
                using (var pen = new Pen(Color.Black, 2))
                {
                    g.DrawRectangle(pen, rect);
                }

                // 绘制方块名称
                using (var font = new Font("Microsoft YaHei", 10))
                using (var brush = new SolidBrush(Color.White))
                {
                    var textSize = g.MeasureString(block.Name, font);
                    var textX = rect.X + (rect.Width - textSize.Width) / 2;
                    var textY = rect.Y + (rect.Height - textSize.Height) / 2;
                    g.DrawString(block.Name, font, brush, textX, textY);
                }
            }
        }

        /// <summary>
        /// 棋盘鼠标点击事件
        /// </summary>
        private void BoardPanel_MouseClick(object sender, MouseEventArgs e)
        {
            if (!isPlacingBlock || selectedBlock == null)
                return;

            int gridX = e.X / 80;
            int gridY = e.Y / 80;

            if (gridX >= 0 && gridX < GameBoard.BOARD_WIDTH && 
                gridY >= 0 && gridY < GameBoard.BOARD_HEIGHT)
            {
                // 检查是否可以放置方块
                if (CanPlaceBlock(selectedBlock, gridX, gridY))
                {
                    selectedBlock.X = gridX;
                    selectedBlock.Y = gridY;
                    gameBoard.AddBlock(selectedBlock);
                    selectedBlock = null;
                    isPlacingBlock = false;
                    ((Panel)sender).Invalidate();
                }
                else
                {
                    MessageBox.Show("无法在此位置放置方块，位置已被占用或超出边界。", 
                        "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        /// <summary>
        /// 开始放置方块
        /// </summary>
        private void StartPlacingBlock()
        {
            var nameTextBox = this.Controls.Find("nameTextBox", true)[0] as TextBox;
            var blockTypeComboBox = this.Controls.Find("blockTypeComboBox", true)[0] as ComboBox;
            var colorComboBox = this.Controls.Find("colorComboBox", true)[0] as ComboBox;

            if (nameTextBox == null || blockTypeComboBox == null || colorComboBox == null)
                return;

            // 创建新方块
            selectedBlock = CreateBlockFromSelection(blockTypeComboBox.SelectedIndex, colorComboBox.SelectedIndex);
            isPlacingBlock = true;

            MessageBox.Show("请点击棋盘上的位置来放置方块。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 根据选择创建方块
        /// </summary>
        private Block CreateBlockFromSelection(int blockTypeIndex, int colorIndex)
        {
            string name = "";
            int width = 1, height = 1;
            bool isCaoCao = false;

            switch (blockTypeIndex)
            {
                case 0: // 曹操
                    name = "曹操";
                    width = 2;
                    height = 2;
                    isCaoCao = true;
                    break;
                case 1: // 关羽
                    name = "关羽";
                    width = 2;
                    height = 1;
                    break;
                case 2: // 张飞
                    name = "张飞";
                    width = 2;
                    height = 1;
                    break;
                case 3: // 赵云
                    name = "赵云";
                    width = 2;
                    height = 1;
                    break;
                case 4: // 马超
                    name = "马超";
                    width = 2;
                    height = 1;
                    break;
                case 5: // 黄忠
                    name = "黄忠";
                    width = 2;
                    height = 1;
                    break;
                case 6: // 兵卒
                    name = "兵卒";
                    width = 1;
                    height = 1;
                    break;
            }

            Color color = GetColorFromIndex(colorIndex);

            return new Block(nextBlockId++, name, 0, 0, width, height, color, isCaoCao);
        }

        /// <summary>
        /// 根据索引获取颜色
        /// </summary>
        private Color GetColorFromIndex(int index)
        {
            switch (index)
            {
                case 0: return Color.Red;
                case 1: return Color.Blue;
                case 2: return Color.Green;
                case 3: return Color.Yellow;
                case 4: return Color.Purple;
                case 5: return Color.Orange;
                case 6: return Color.Cyan;
                default: return Color.Gray;
            }
        }

        /// <summary>
        /// 检查是否可以放置方块
        /// </summary>
        private bool CanPlaceBlock(Block block, int x, int y)
        {
            // 检查边界
            if (x < 0 || y < 0 || x + block.Width > GameBoard.BOARD_WIDTH || y + block.Height > GameBoard.BOARD_HEIGHT)
                return false;

            // 检查是否与其他方块重叠
            for (int i = 0; i < block.Width; i++)
            {
                for (int j = 0; j < block.Height; j++)
                {
                    if (gameBoard.GetBlockAt(x + i, y + j) != null)
                        return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 清除棋盘
        /// </summary>
        private void ClearBoard()
        {
            if (MessageBox.Show("确定要清除棋盘上的所有方块吗？", "确认", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                gameBoard.Clear();
                nextBlockId = 1;
                this.Invalidate();
            }
        }

        /// <summary>
        /// 保存布局
        /// </summary>
        private void SaveLayout()
        {
            var nameTextBox = this.Controls.Find("nameTextBox", true)[0] as TextBox;
            if (nameTextBox == null)
                return;

            if (string.IsNullOrWhiteSpace(nameTextBox.Text))
            {
                MessageBox.Show("请输入布局名称。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (gameBoard.Blocks.Count == 0)
            {
                MessageBox.Show("请至少添加一个方块。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 检查是否有曹操方块
            var caoBlock = gameBoard.Blocks.FirstOrDefault(b => b.IsCaoCao);
            if (caoBlock == null)
            {
                MessageBox.Show("请添加曹操方块（2x2）。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                // 创建布局
                customLayout.Name = nameTextBox.Text;
                customLayout.Description = "自定义布局";
                customLayout.Difficulty = 1;
                
                // 转换方块为方块定义
                customLayout.BlockDefinitions.Clear();
                foreach (var block in gameBoard.Blocks)
                {
                    var blockDef = new BlockDefinition(
                        block.Id, block.Name, block.Width, block.Height, 
                        block.X, block.Y, block.Color, block.IsCaoCao);
                    customLayout.BlockDefinitions.Add(blockDef);
                }

                // 保存布局
                if (HuaRongDaoGame.Services.GameDataService.SaveCustomLayout(customLayout))
                {
                    MessageBox.Show("布局保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show("保存布局失败。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("保存布局时出错：{0}", ex.Message), 
                    "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
} 